/**
 * Created by apple on 2017/9/30.
 */
var DBFactory = require('../db/mysql_db');
var RecommenderDao = module.exports;
var Config = require('../config');

//查询全部下级    agent_lvl 具体第几级下线 1下级 2下下级 3区代 4市代 5省代。 没传默认查全部
RecommenderDao.getSubordinate = function (data,cb) {

    if (!data) return cb(new Error(500));

    data.subordinateInfo = {};

    var startIndex = -1;
    if((data.agent_lvl > 1 && data.agent_lvl <= 6) || (data.agent_lvl == -2) ){
        startIndex = data.agent_lvl;
    }

    findTotalSubordinate(data,startIndex,function (err) {
        if(err) return cb(err);
        cb(null,data.subordinateInfo);
    });

}

//查询下级，index = -2：间接推荐人，-1：推荐人， 1-6：代理级别
function findTotalSubordinate(data,index,callback) {
    if(index >= 5){
        callback(null,null);
        return;
    }
    var sql = 'SELECT account FROM user_app_new_agent WHERE ';
    if(index == -1){
        sql = 'SELECT account FROM user_app_new_agent WHERE recommender = ? AND app_sid = ? ';
    }
    else if(index == -2){
        sql = 'SELECT account FROM user_app_new_agent WHERE recommender2 = ? AND app_sid = ? ';
    }
    else if(index > 0 && index <= 6){
        sql = 'SELECT account FROM user_app_new_agent WHERE agent_' + index + ' = ? AND app_sid = ? ';
    }
    DBFactory.poolQuery(sql, [data.account,data.app_key],
        function () {
            callback('no collection');
        },
        function (err, result) {
            if (err) {
                console.log(err);
                callback(err);
                return;
            }

            data.subordinateInfo['lowAccountInfo'] = [];
            result.forEach(function (accountInfo) {
                data.subordinateInfo['lowAccountInfo'].push(accountInfo.account);
            });
            callback(null,null);    //不再支持无限级查询
        }
    );
}

RecommenderDao.getCommissionRate = function (data,cb) {

    if (!data) return cb(new Error(500));

    DBFactory.poolQuery('SELECT commission_rate1 FROM app_agent WHERE app_sid = ? ', [data.app_key],
        function () {
            cb('no collection');
        },
        function (err, result) {
            if (err) {
                console.log(err);
                cb(err);
                return;
            }
            cb(null, result);
        }
    );

}

RecommenderDao.getFirstSubInfo = function (data,cb) {
    if (!data) return cb(new Error(500));
    var isCompanyAccount = (data.uid == Config.USUZ_COMPANY_UID && !data.isFindByAccount);
    var value = [data.app_sid];
    var sql;
    if (data.isFindByAccount) {
        sql = "SELECT  uaa.created_time,uaa.account,uae.real_sub_ea as team_num,uv.vip_sid AS isVip,uaa.score,uaa.money,uaa.freeze_money," +
            "ISNULL(uaa.uuid) AS unLogin,uaa.is_show_up,uaa.uid,uae.ali_user_id  " +
            "FROM user_app_new_agent uaa LEFT JOIN " +
            "user_vip uv ON uaa.account = uv.account AND uv.app_sid = uaa.app_sid " +
            "LEFT JOIN user_app_exInfo uae ON uaa.account = uae.account AND uaa.app_sid = uae.app_sid " +
            "WHERE uaa.app_sid = ? "
    }else {
        sql = "SELECT  uae.real_sub_ea as team_num,uaa.created_time,uaa.account,uaa.is_show_up,uaa.uid,uv.vip_sid AS isVip,ISNULL(uaa.uuid) AS unLogin,uae.ali_user_id,uaa.score,uaa.money,uaa.freeze_money " +
            " FROM user_app_new_agent uaa LEFT JOIN " +
            "user_vip uv ON uaa.account = uv.account AND uv.app_sid = uaa.app_sid " +
            "LEFT JOIN user_app_exInfo uae ON uaa.account = uae.account AND uaa.app_sid = uae.app_sid " +
            " WHERE uaa.app_sid = ? "
    }
    var countSql = "SELECT COUNT(A.isVip) AS vipCount,COUNT(*) AS totalCount from " +
        "(SELECT uv.vip_sid as isVip FROM user_app_new_agent uaa LEFT JOIN " +
        "user_vip uv ON uaa.account = uv.account AND uv.app_sid = uaa.app_sid WHERE  uaa.app_sid = ? ";

    if (!isCompanyAccount) {
        sql += "AND uaa.recommender = ? ";
        countSql += "AND uaa.recommender = ? ";
        value.push(data.account);
    }
    if (data.isFindByAccount && data.subAccount) {
        sql += "AND uaa.account LIKE ? ";
        countSql += "AND uaa.account LIKE ? ";
        value.push('%' + data.subAccount + '%');
    }
    sql += " GROUP BY uaa.account ";
    sql += isCompanyAccount ? "ORDER BY uaa.team_num DESC " : "ORDER BY uaa.created_time DESC ";
    countSql += " GROUP BY uaa.account) A ";
    var pageSize = data.pageSize ? data.pageSize : 10;
    var page = data.page ? data.page : 1;
    sql += 'limit ' + (page - 1) * pageSize + ',' + pageSize;
    DBFactory.getConnection(function (error, connection) {
        if (error) {
            cb(error);
            return;
        }
        connection.query(sql, value, function (err, result) {
            if (err) {
                cb(err);
                connection.release();
                return;
            }
            // result.forEach(function (info) {
            //     info.create_time = simpleDateFormat(info.create_time);
            //     if(data.isFindByAccount && info.account >= 11){
            //         info.account = info.account.substr(0,3) + '****' + info.account.substr(7,4);
            //     }
            // });
            var teamInfo = {
                subList: (result && result.length > 0) ? result : null,
            };
            connection.query(countSql, value, function (err, result) {
                if (err) {
                    cb(err);
                    connection.release();
                    return;
                }
                teamInfo.totalCount = ( result && result[0] ) ? result[0].totalCount : 0;
                teamInfo.vipCount = ( result && result[0] ) ? result[0].vipCount : 0;
                cb(null, teamInfo);
                connection.release();
            });
        });
    });
}

RecommenderDao.findRecommenderInfo = function (data,cb) {
    if (!data) return cb(new Error(500));
    DBFactory.poolQuery('SELECT agent_1, agent_2, agent_3, agent_4, agent_5, agent_6' +
        ' FROM user_app_new_agent WHERE uid = ? AND app_sid = ? ', [data.recommendUid,data.app_key],
        function () {
            cb('no collection');
        },
        function (err, result) {
            if (err) {
                console.log(err);
                cb(err);
                return;
            }
            if(result && result[0]){
                cb(null, result[0]);
                return;
            }else {
                cb(null,{});
            }

        }
    );
}

RecommenderDao.giveUpVip = function (data,cb) {
    if (!data) return cb(new Error(500));

    DBFactory.getConnection(function (error, connection) {
        if (error) {
            cb(error);
            return;
        }
        connection.query('SELECT recommender,recommender2,is_show_up FROM user_app_new_agent WHERE uid = ? AND app_sid = ? ', [data.person_uid,data.app_sid], function (err, result) {
            if (err) {
                cb(err);
                connection.release();
                return;
            }
            var userInfo = ( result && result[0] ) ? result[0] : undefined;
            if(!userInfo){
                cb('该用户不存在');
                connection.release();
                return;
            }
            if(userInfo.recommender != data.recommender && userInfo.recommender2 != data.recommender){
                cb('无权限');
                connection.release();
                return;
            }
            if(userInfo.is_show_up == 1){
                cb('重复赋予');
                connection.release();
                return;
            }
            connection.query('UPDATE user_app_new_agent SET is_show_up = 1 WHERE uid = ? AND app_sid = ? ', [data.person_uid,data.app_sid], function (err, result) {
                if (err) {
                    cb(err);
                    connection.release();
                    return;
                }
                if(result.affectedRows > 0){
                    cb(null,'赋予成功');
                }else {
                    cb('赋予失败');
                }
                connection.release();
            });
        });
    });
}